import {defineComponent, onMounted, ref} from "vue";
import { ElTree, ElLoading } from "element-plus"
import {useGroupListApi, useOrgList3Api} from "@/api/sys/orgs";
import {Company, Group} from "@/interface/home";
import {arrayToTree, insertArrayIntoTree} from "@/components/tree/tree_tools";
import {useUserStore} from "@/store/modules/user";

export default defineComponent({
    name: 'GenericOrgTree',
    props: {
      group: {
          type: Boolean,
          default: false
      },
      automatic: {
          type: Boolean,
          default: false
      }
    },
    setup(props, { slots, attrs , expose}) {
        const userStore = useUserStore()
        const treeRef =  ref<InstanceType<typeof ElTree>>()
        const treeMethods = ref({});
        console.log(attrs, slots)
        const treeData = ref<any[]>([])
        const treeLoading = ref(false)
        let loadingInstance
        onMounted(()=>{
            // 遍历el-tree实例上所有key，筛选出方法
            // @ts-ignore
            const refMethods = Object.entries(treeRef.value).filter(
                ([_, value]) => value instanceof Function
            );
            refMethods.forEach(([key, value]) => {
                treeMethods.value[key] = value;
            });
            // 额外添加一个本组件的初始化方法
            treeMethods.value["init"] = init
            loadingInstance = ElLoading.service({
                target: treeRef.value?.$el
            })

            props.automatic && init()
        })


        async function init(...rest: Promise<any>[]){
            // treeLoading.value = true
            let data: any[] = []
            await Promise.all([useOrgList3Api({onlyVideo: false}), useGroupListApi(), ...rest]).then(res =>{
                const institutions: Company[] = arrayToTree(res[0].data.map(item => {
                    return {
                        nodeType: "company",
                        name: item.name,
                        id: item.id,
                        nodeId: "i-" + item.id,
                        parentId: item.pid,
                        totalDeviceNum: item.totalDeviceNum,
                        onlineDeviceNum: item.onlineDeviceNum,
                        totalDeviceOnlineNum: item.totalDeviceOnlineNum,
                        deviceOnlineNum: item.deviceOnlineNum,
                        children: []
                    }
                }), "company", userStore.user.orgId)

                const groups: Group[] = arrayToTree(res[1].data.map(item =>{
                    return {
                        nodeType: "group",
                        name: item.name,
                        deptId: item.deptId,
                        id: item.id,
                        nodeId: "g-" + item.id,
                        parentId: item.parentId,
                        totalDeviceNum: item.totalDeviceNum,
                        onlineDeviceNum: item.onlineDeviceNum,
                        children: []
                    }
                }), "group")

                props.group && insertArrayIntoTree(institutions, groups)

                treeData.value = institutions
                data = res.slice(2)
            })
            loadingInstance.close()
            return data
        }

        expose(treeMethods.value)


        return ()=> <ElTree ref={treeRef}
                            data={treeData.value}
                            {...attrs}
                            v-slots={slots}>
        </ElTree>
    }
})